<template>
  <div class="table-all">
    <!-- 搜索区 -->
    <div class="app-container search-box">
      <SearchForm
        :form="searchData.form"
        :options="searchData.options"
        @searchUpdate="search"
        @resetSearchData="resetSearchData"
      ></SearchForm>
    </div>
    <!-- 按钮区 -->
    <div class="app-container table-box">
      <div class="table-main">
        <!-- 表格 -->
        <v-table
          :title="this.$commonJs.getModeName(this.$route.path) + '设备实时监测数据信息'"
          v-if="tableMainHeight>0"
          :table-columns="tableColumns"
          :table-data="tableData"
          :loading="loading"
          :is-index="true"
          ref="table"
          :maxHeight="tableMainHeight">
          <template #topButtonList>
            <ButtonForm :buttonList="buttonList" @clickButton="clickButton"></ButtonForm>
          </template>
          <template #deviceType="scope">
            {{ getDictValue(scope.row.deviceType, deviceTypeOptions) }}
          </template>
          <template #monitorType="scope">
            {{ getDictValue(scope.row.monitorType, monitorTypeOptions) }}
          </template>
          <template #paramValueList="scope">
            {{ paramValueListFormat(scope.row.paramValueList) }}
          </template>
          <template #operation="scope">
            <a v-hasPermission="['alarmRealHistory:add']" class="table-btn-edit table-operation"
               @click="handleEdit(scope.row)">{{$t('table.edit')}}</a>
            <a class="table-btn-view table-operation" @click="handleDetail(scope.row)">{{$t('table.view')}}</a>
            <a v-hasPermission="['alarmRealHistory:delete']" class="table-btn-delete table-operation"
               @click="singleDelete(scope.row)">{{$t('table.delete')}}</a>
          </template>
        </v-table>
      </div>
      <div class="table-page">
        <!-- 页码 -->
        <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                    @pagination="search"/>
      </div>
    </div>
    <!-- 详情 -->
    <detailDialog :dialog-visible="detailDialogShow"
                  @success="editSuccess"
                  @close="editClose"
                  :openType="detailOpenType"
                  :id="detailId"
                  :title="detailTitle"
    ></detailDialog>
  </div>
</template>

<script>
import {
  alarmRealHistoryPage,
  alarmRealHistoryExport,
  alarmRealHistoryDelete
} from '@/api/alarm/history'
import SearchForm from '@/components/searchForm'
import ButtonForm from '@/components/ButtonForm'
import VTable from '@/components/VTable'
import Pagination from '@/components/Pagination'
import detailDialog from './detail.vue'

export default {
  components: {
    VTable, Pagination, detailDialog, SearchForm, ButtonForm
  },
  data() {
    return {
      modeType: '',
      title: '',

      tableColumns: [
        // {
        //   prop: 'pointIdentificationCode',
        //   label: '点位标识码',
        //   minWidth: '150',
        //   slotname: 'pointIdentificationCode',
        //   options: {}
        // },
        {
          prop: 'projectName',
          label: '所属工地',
          minWidth: '150',
          slotname: 'projectName',
          options: {}
        },
        {
          prop: 'facilityName',
          label: '设施名称',
          minWidth: '150',
          slotname: 'facilityName',
          options: {}
        },

        {
          prop: 'pointName',
          label: '点位名称',
          minWidth: '150',
          slotname: 'pointName',
          options: {}
        },

        {
          prop: 'deviceName',
          label: '监测设备名称',
          minWidth: '150',
          slotname: 'deviceName',
          options: {}
        },

        {
          prop: 'monitorType',
          label: '监测类型',
          minWidth: '150',
          slotname: 'monitorType',
          options: {}
        },

        {
          prop: 'paramValueList',
          label: '监测项值',
          minWidth: '150',
          slotname: 'paramValueList',
          options: {}
        },
        // {
        //   prop: 'identificationCode',
        //   label: '标识码',
        //   minWidth: '150',
        //   slotname: 'identificationCode',
        //   options: {}
        // },

        {
          prop: 'createTime',
          label: '上报时间',
          minWidth: '150',
          slotname: 'createTime',
          options: {}
        },


        {
          prop: 'operation',
          label: '操作',
          width: '200',
          align: 'center',
          slotname: 'operation',
          overflow: false,
          fixed: 'right'
        }
      ],
      tableData: [],
      selection: [],
      loading: false,
      total: 1,
      pageNum: 1,
      pageSize: 10,
      detailOpenType: "add",
      detailDialogShow: false,
      detailId: "",
      detailTitle: this.title + "新增",
      dict: {},
      searchData: {
        form: {
          modeType: this.modeType,
          deviceName: '',
          deviceType: '',
          monitorType: '',
          facilityName: '',
          pointName: '',
        },
        options: [
          {
            title: '设备名称',
            key: "deviceName",
            type: "text",
          },
          {
            title: '设施名称',
            key: "facilityName",
            type: "text",
          },
          {
            title: '监测点位名称',
            key: "pointName",
            type: "text",
          },
        ]
      },
      buttonList: [
        {name:'新增',methods:'handleAdd',type:'primary', hasPremission:["alarmRealHistory:add"]},
        {name: '导出数据', methods: 'handleExport',type:'primary', hasPremission:["alarmRealHistory:export"] }
      ],
      tableMainHeight: 0,
      // 字典
      equipmentTypeOptions: [],
      deviceTypeOptions: [],
      monitorTypeOptions: [],
      eventTypeOptions: [],
    }
  },
  watch: {
    // 字典
    'modeType': {
      handler(newVal, oldVal) {
        this.searchData.form.modeType = newVal;
      },
      deep: true,
      immediate: true
    },
    'deviceTypeOptions': {
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t => {
          if (t.key == 'deviceType') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'monitorTypeOptions': {
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t => {
          if (t.key == 'monitorType') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    paramValueListFormat(value){
      if(value!=null){
        return JSON.parse(value).map(t=>{
          return "监测项："+t.itemName+",监测值："+t.itemValue
        }).join(";")
      }
      return ''
    },
    getCheckBoxValue(value, option) {
      if (!value) {
        return
      }
      let temp = []
      let data = value.split(",")
      data.forEach(t => {
        let item = option.find(x => x.value == t)
        if (item != undefined) {
          temp.push(item.label)
        }
      })
      return temp.join(",")
    },
    getDictValue(value, option) {
      let item = option.find(t => t.value == value)
      if (item != undefined) {
        return item.label
      }
      return value
    },
    editClose() {
      this.detailDialogShow = false
    },
    editSuccess() {
      this.search()
      this.detailDialogShow = false
    },
    search() {
      this.fetch({
        ...this.searchData.form,
      })
    },
    fetch(params = {}) {
      params.pageSize = this.pageSize
      params.pageNum = this.pageNum
      // 添加区域标识
      //params.areaCode = this.$store.state.account.user.deptIds
      this.loading = true
      params.modeType = this.modeType != '' ? this.modeType : this.$commonJs.getAlarmPathConfig(this.$route.path).modeTypeSs
      alarmRealHistoryPage(params).then(res => {
        if (res.code == 200) {
          this.total = res.data.total
          this.tableData = res.data.rows
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      }).finally(final => {
        this.loading = false
      })
    },
    // 重置搜索条件
    resetSearchData() {
      this.searchData.form = {
        modeType: this.modeType,
        deviceName: '',
        deviceType: '',
        monitorType: '',
        facilityName: '',
        pointName: '',
      }
    },

    // 触发按钮区域按钮方法
    clickButton(methods) {
      this[methods]()
    },
    handleAdd() {
      this.detailOpenType = "add"
      this.detailTitle = this.title + "新增"
      this.detailDialogShow = true
    },
    handleEdit(row) {
      this.detailId = row.id
      this.detailOpenType = "edit"
      this.detailTitle = this.title + "编辑"
      this.detailDialogShow = true
    },
    handleDetail(row){
      this.detailId = row.id
      this.detailOpenType = "detail"
      this.detailTitle = this.title + "详情"
      this.detailDialogShow = true
    },
    handleExport() {
      let params = {
        ...this.searchData.form,
        areaCode: this.$store.state.account.user.deptIds
      }
      const config = this.$commonJs.getAlarmPathConfig(this.$route.path)
      alarmRealHistoryExport(params, `${config.hTitle}_设备实时监测数据_${new Date().getTime()}.xlsx`);
    },
    handleImport() {
      console.log("等待处理")
    },
    closeDialog() {
      this.detailDialogShow = false
    },

    singleDelete(row) {
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.loading = true
        alarmRealHistoryDelete(row.id).then(res => {
          if (res.code == 200) {
            this.$message({
              message: this.$t('tips.deleteSuccess'),
              type: 'success'
            })
            this.search()
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        }).finally(final => {
          this.loading = false
        })
      })
    },
    initAlarmConfig() {
      let type = this.$route.path
      console.log("path:" + type)
      const config = this.$commonJs.getAlarmPathConfig(this.$route.path)
      this.modeType = config.modeTypeSs
      this.title = config.hTitle
    }
  },
  activated() {
    this.fetch()
  },
  created() {
    this.initAlarmConfig()
    // 获取字典值
    this.fetch()
  },
  mounted() {
    this.tableMainHeight = document.getElementsByClassName('table-main')[0].clientHeight - 44 //减去顶部按钮列表的高度
  }
}
</script>

<style lang="scss" scoped>
.table-all {
  display: flex;
  flex-direction: column;
  height: 100%;

  .search-box {
    padding-bottom: 6px;
  }

  .table-box {
    padding-top: 10px;
    flex: 1;
    display: flex;
    flex-direction: column;

    .table-main {
      flex: 1;
      overflow: auto;
    }

    .table-page {
      // padding-top: 10 px;
      // padding-bottom: 10 px;
    }

    ::v-deep .pagination-container {
      text-align: right;
    }

  }
}
</style>
